export class ChromeStorage {
  private storage: typeof chrome.storage.local

  constructor() {
    this.storage = chrome.storage.local
  }

  async get(key: string): Promise<any> {
    return new Promise((resolve, reject) => {
      this.storage.get(key, (result) => {
        if (chrome.runtime.lastError) {
          reject(new Error(`获取本地存储数据时出错: ${chrome.runtime.lastError.message}`))
        }
        else {
          resolve(result[key])
        }
      })
    })
  }

  async set(key: string, value: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const dataToStore = {} as Record<string, unknown>
      dataToStore[key] = value

      this.storage.set(dataToStore, () => {
        if (chrome.runtime.lastError) {
          reject(new Error(`设置本地存储数据时出错: ${chrome.runtime.lastError.message}`))
        }
        else {
          resolve(true)
        }
      })
    })
  }

  async clear(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.storage.clear(() => {
        if (chrome.runtime.lastError) {
          reject(new Error(`清除本地存储数据时出错: ${chrome.runtime.lastError.message}`))
        }
        else {
          resolve()
        }
      })
    })
  }

  async remove(keys: string | string[]): Promise<void> {
    return new Promise((resolve, reject) => {
      this.storage.remove(keys, () => {
        if (chrome.runtime.lastError) {
          reject(new Error(`删除本地存储数据时出错: ${chrome.runtime.lastError.message}`))
        }
        else {
          resolve()
        }
      })
    })
  }

  async getAll(): Promise<{ [key: string]: any }> {
    return new Promise((resolve, reject) => {
      this.storage.get(null, (result) => {
        if (chrome.runtime.lastError) {
          reject(new Error(`获取本地存储所有数据时出错: ${chrome.runtime.lastError.message}`))
        }
        else {
          resolve(result)
        }
      })
    })
  }
}

/**
 * 用法如下
 */
// const chromeStorage = new ChromeStorage();

// 获取指定键的值
// const result = await chromeStorage.get('myKey')

// 设置指定键的值
// await chromeStorage.set('myKey', 'myValue')

// 清除所有本地存储数据
// await chromeStorage.clear()

// 删除指定的键值对
// await chromeStorage.remove('key')
// await chromeStorage.remove(['key1', 'key2'])

// 获取所有数据
// const result = chromeStorage.getAll()
